/**
 * 移动端交互优化工具函数
 */

// 防抖函数
export function debounce<T extends (...args: any[]) => any>(
  func: T,
  wait: number
): (...args: Parameters<T>) => void {
  let timeout: NodeJS.Timeout;
  return function executedFunction(...args: Parameters<T>) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
}

// 节流函数
export function throttle<T extends (...args: any[]) => any>(
  func: T,
  limit: number
): (...args: Parameters<T>) => void {
  let inThrottle: boolean;
  return function executedFunction(...args: Parameters<T>) {
    if (!inThrottle) {
      func.apply(this, args);
      inThrottle = true;
      setTimeout(() => (inThrottle = false), limit);
    }
  };
}

// 触觉反馈
export function hapticFeedback(type: 'light' | 'medium' | 'heavy' = 'light') {
  // #ifdef APP-PLUS
  plus.device.vibrate(type === 'light' ? 15 : type === 'medium' ? 40 : 80);
  // #endif
  
  // #ifdef H5
  if (navigator.vibrate) {
    const duration = type === 'light' ? 10 : type === 'medium' ? 20 : 50;
    navigator.vibrate(duration);
  }
  // #endif
}

// 安全区域适配
export function getSafeAreaInsets() {
  return new Promise((resolve) => {
    uni.getSystemInfo({
      success: (res) => {
        const safeArea = res.safeArea || {};
        const safeAreaInsets = res.safeAreaInsets || {};
        resolve({
          top: safeAreaInsets.top || 0,
          bottom: safeAreaInsets.bottom || 0,
          left: safeAreaInsets.left || 0,
          right: safeAreaInsets.right || 0,
        });
      },
      fail: () => {
        resolve({ top: 0, bottom: 0, left: 0, right: 0 });
      },
    });
  });
}

// 图片预加载
export function preloadImages(urls: string[]): Promise<void[]> {
  const promises = urls.map((url) => {
    return new Promise<void>((resolve, reject) => {
      const img = new Image();
      img.onload = () => resolve();
      img.onerror = () => reject(new Error(`Failed to load image: ${url}`));
      img.src = url;
    });
  });
  return Promise.all(promises);
}

// 格式化文件大小
export function formatFileSize(bytes: number): string {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 复制到剪贴板
export function copyToClipboard(text: string): Promise<void> {
  return new Promise((resolve, reject) => {
    uni.setClipboardData({
      data: text,
      success: () => {
        uni.showToast({
          title: '复制成功',
          icon: 'success',
        });
        resolve();
      },
      fail: (error) => {
        uni.showToast({
          title: '复制失败',
          icon: 'none',
        });
        reject(error);
      },
    });
  });
}

// 分享功能
export function shareContent(options: {
  title?: string;
  summary?: string;
  href?: string;
  imageUrl?: string;
}) {
  // #ifdef APP-PLUS
  uni.share({
    provider: 'weixin',
    scene: 'WXSceneSession',
    type: 0,
    ...options,
    success: () => {
      uni.showToast({
        title: '分享成功',
        icon: 'success',
      });
    },
    fail: (error) => {
      console.error('分享失败:', error);
      uni.showToast({
        title: '分享失败',
        icon: 'none',
      });
    },
  });
  // #endif
  
  // #ifdef H5
  if (navigator.share) {
    navigator.share(options).catch((error) => {
      console.error('分享失败:', error);
    });
  } else {
    // 降级处理：复制链接
    if (options.href) {
      copyToClipboard(options.href);
    }
  }
  // #endif
}

// 下拉刷新优化
export function createPullRefresh(callback: () => Promise<void>) {
  let isRefreshing = false;
  
  return async () => {
    if (isRefreshing) return;
    
    isRefreshing = true;
    hapticFeedback('light');
    
    try {
      await callback();
    } finally {
      isRefreshing = false;
    }
  };
}

// 上拉加载优化
export function createLoadMore(callback: () => Promise<void>) {
  let isLoading = false;
  
  return async () => {
    if (isLoading) return;
    
    isLoading = true;
    
    try {
      await callback();
    } finally {
      isLoading = false;
    }
  };
}

// 长按操作
export function createLongPress(callback: () => void, duration = 500) {
  let timer: NodeJS.Timeout;
  let isPressed = false;
  
  const start = () => {
    isPressed = true;
    timer = setTimeout(() => {
      if (isPressed) {
        hapticFeedback('medium');
        callback();
      }
    }, duration);
  };
  
  const end = () => {
    isPressed = false;
    clearTimeout(timer);
  };
  
  return { start, end };
}

// 滑动手势
export interface SwipeOptions {
  threshold?: number;
  onSwipeLeft?: () => void;
  onSwipeRight?: () => void;
  onSwipeUp?: () => void;
  onSwipeDown?: () => void;
}

export function createSwipeGesture(options: SwipeOptions) {
  const { threshold = 50 } = options;
  let startX = 0;
  let startY = 0;
  let endX = 0;
  let endY = 0;
  
  const touchStart = (e: TouchEvent) => {
    startX = e.touches[0].clientX;
    startY = e.touches[0].clientY;
  };
  
  const touchEnd = (e: TouchEvent) => {
    endX = e.changedTouches[0].clientX;
    endY = e.changedTouches[0].clientY;
    
    const deltaX = endX - startX;
    const deltaY = endY - startY;
    
    if (Math.abs(deltaX) > Math.abs(deltaY)) {
      // 水平滑动
      if (Math.abs(deltaX) > threshold) {
        if (deltaX > 0) {
          options.onSwipeRight?.();
        } else {
          options.onSwipeLeft?.();
        }
      }
    } else {
      // 垂直滑动
      if (Math.abs(deltaY) > threshold) {
        if (deltaY > 0) {
          options.onSwipeDown?.();
        } else {
          options.onSwipeUp?.();
        }
      }
    }
  };
  
  return { touchStart, touchEnd };
}

// 网络状态检测
export function getNetworkType(): Promise<string> {
  return new Promise((resolve) => {
    uni.getNetworkType({
      success: (res) => {
        resolve(res.networkType);
      },
      fail: () => {
        resolve('unknown');
      },
    });
  });
}

// 设备信息获取
export function getDeviceInfo(): Promise<any> {
  return new Promise((resolve) => {
    uni.getSystemInfo({
      success: (res) => {
        resolve({
          platform: res.platform,
          system: res.system,
          version: res.version,
          screenWidth: res.screenWidth,
          screenHeight: res.screenHeight,
          windowWidth: res.windowWidth,
          windowHeight: res.windowHeight,
          pixelRatio: res.pixelRatio,
          statusBarHeight: res.statusBarHeight,
          safeArea: res.safeArea,
          safeAreaInsets: res.safeAreaInsets,
        });
      },
      fail: () => {
        resolve({});
      },
    });
  });
}

// 性能监控
export class PerformanceMonitor {
  private marks: Map<string, number> = new Map();
  
  mark(name: string) {
    this.marks.set(name, Date.now());
  }
  
  measure(startMark: string, endMark?: string): number {
    const startTime = this.marks.get(startMark);
    const endTime = endMark ? this.marks.get(endMark) : Date.now();
    
    if (!startTime) {
      console.warn(`Performance mark "${startMark}" not found`);
      return 0;
    }
    
    const duration = (endTime || Date.now()) - startTime;
    console.log(`Performance: ${startMark} took ${duration}ms`);
    return duration;
  }
  
  clear() {
    this.marks.clear();
  }
}

export const performanceMonitor = new PerformanceMonitor();